package com.filldream.fastboot.common.stockUtils.ths;

import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.filldream.fastboot.common.constant.enums.StockFstEnum;
import com.filldream.fastboot.common.constant.enums.StockMarketUtil;
import com.filldream.fastboot.common.okutil.stock.cf.kline.GetKLineSTO;
import com.filldream.fastboot.common.okutil.stock.cf.kline.KLineDTO;
import com.filldream.fastboot.common.okutil.stock.cf.kline.KLineItemDTO;
import com.filldream.fastboot.common.stockUtils.StockCommonUtil;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 同花顺相关工具
 */
public class ThsUtil {

    /**
     * 获取分时图数据
     * 废弃：因为均价不准以及速度慢
     * @param sto   请求参数
     * @return  分时图所需数据
     */
    public static KLineDTO getFst(GetKLineSTO sto){
        String thsCode = StockMarketUtil.getThsKLineCode(sto.getSearchCode());
        String urlResult = HttpUtil.get("https://d.10jqka.com.cn/v6/time/"+thsCode+"/last.js");
        urlResult = urlResult.replaceAll(  "quotebridge_v6_time_"+thsCode+"_last\\(" ,"");
        urlResult = urlResult.substring( 0,urlResult.length() - 1 );
        urlResult = UnicodeUtil.toString(urlResult);
        JSONObject parentJsonObject = JSONObject.parseObject(urlResult);
        JSONObject jsonObject = parentJsonObject.getJSONObject(thsCode);
        KLineDTO result = new KLineDTO();
        result.setCodePrefix(sto.getSearchCode().substring(0,2));
        result.setPreClosePrice(jsonObject.getBigDecimal("pre"));
        result.setPriceDecimal(Math.max(result.getPreClosePrice().scale(),2));
        result.setCfKLineType( StockFstEnum.getByType(sto.getType()).getCfKType() );
        String data = jsonObject.getString("data");
        String[] split = data.split(";");
        List<KLineItemDTO> itemList = new ArrayList<>();
        for (String item : split) {
            String[] stockPriceItem = item.split(",");
            KLineItemDTO kLineItem = new KLineItemDTO();
            kLineItem.setDate( stockPriceItem[0].substring(0,2) + ":" + stockPriceItem[0].substring(2,4)  );
            kLineItem.setPrice( new BigDecimal(stockPriceItem[1]));
            kLineItem.setVolume( new BigDecimal(stockPriceItem[2]));
            kLineItem.setAvgPrice( new BigDecimal(stockPriceItem[3]) );
            kLineItem.setZdf(StockCommonUtil.getZdf( result.getPreClosePrice(),kLineItem.getPrice() ));
            kLineItem.setZde( kLineItem.getPrice().subtract(result.getPreClosePrice())  );
            result.initPriceAndAvgPriceZdf(kLineItem.getZdf());
            result.initPriceAndAvgPriceZdf(StockCommonUtil.getZdf( result.getPreClosePrice(),kLineItem.getAvgPrice() ));
            itemList.add( kLineItem );
        }
        result.setList(itemList);
        result.initHumanVolume();
        return result;
    }

}
